package com.mediacloud.app.newsmodule.fragment.video.vod

import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.IEvent
import com.mediacloud.app.newsmodule.fragment.BigVideoViewHolder
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils


class VideoNewListAdapterX(val context: Context) : RecyclerView.Adapter<BigVideoViewHolder>(),
    View.OnClickListener {

    var data: MutableList<ArticleItem> = ArrayList()
    var catalogItem: CatalogItem? = null
    var events: ArrayList<IEvent> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BigVideoViewHolder {
        return BigVideoViewHolder(LayoutInflater.from(context).inflate(R.layout.item_info_flow_big, parent, false))
    }

    fun setItems(data: MutableList<ArticleItem>) {
        this.data.clear()
        this.data.addAll(data)
        notifyDataSetChanged()
    }

    fun addItems(data: MutableList<ArticleItem>) {
        this.data.addAll(data)
        notifyItemRangeInserted(this.data.size - data.size, data.size)

    }


    override fun onBindViewHolder(holder: BigVideoViewHolder, position: Int) {
        val item = data[position]
        if (TextUtils.isEmpty(item.referName))
            holder.tvResourceTime.text = "${item.publishdate_format}"
        else
            holder.tvResourceTime.text = "${item.referName}  ${item.publishdate_format}"

        if (TextUtils.isEmpty(item?.spider_user?.userNickName))
            if(!TextUtils.isEmpty(item?.authorNickName)){
                holder.tvResourceTime.text = "${item.authorNickName}  ${item.publishdate_format}"
            }else{
                holder.tvResourceTime.text = "${context.getResources().getString(R.string.app_name)}  ${item.publishdate_format}"
            }
        else
            holder.tvResourceTime.text = "${item?.spider_user?.userNickName}  ${item.publishdate_format}"

        holder.setInfo(item,position)
        holder.itemView.tag = position
        holder.itemView.setOnClickListener(this)
        events.add(holder)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onClick(v: View?) {
        val position = v?.tag as Int
        val item = data[position] as ArticleItem
        NewsItemClickUtils.OpenItemNewsHandle(
            context,
            item.type,
            item,
            catalogItem ?: CatalogItem()
        )
    }

    fun destroy() {
        for (event in events) {
            event.destroy()
        }
        events.clear()
    }

}